<template>
  <!-- 近6个月效益流失率 -->
  <div class="benefits-loss chart-box2">
    <div class="chart-title">近6个月效益流失率</div>
    <div class="chart-content">
      <div class="chart-container" :id="chartId"></div>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  onBeforeUnmount,
  nextTick,
  toRaw,
  watch,
} from "vue";
import { Chart, registerTheme } from "@antv/g2";
import common from "../../utils/common";
import store from "../../../../store";

export default defineComponent({
  name: "BenefitsLoss",
  components: {},
  setup() {
    const state = reactive({
      chartId: "benefitsLossChart",
      chart: null,
      data: [],
    });

    const initChart = () => {
      const data = state.data;

      state.chart = new Chart({
        container: state.chartId,
        autoFit: true,
        theme: "chartTheme",
      });

      state.chart.data(data);
      state.chart.scale({
        date: {
          range: [0, 1],
        },
        percent: {
          min: 0,
          max: 100,
          formatter: (val) => {
            return val + "%";
          },
        },
      });

      state.chart.tooltip({
        title: (title) => title + "（流失率）",
      });

      state.chart.legend(false);

      state.chart.area().position("date*percent").color("name").shape("smooth");

      state.chart.line().position("date*percent").color("name").shape("smooth");

      state.chart.render();
    };

    watch(
      () => store.getters.rentControl.IncomeLossRate,
      (val) => {
        if (val) {
          getData();
        }
      }
    );

    const getData = () => {
      const { IncomeLossRate } = store.getters.rentControl;
      if (IncomeLossRate) {
        console.log("---------IncomeLossRate", toRaw(IncomeLossRate));
        state.data = IncomeLossRate;
        if (state.chart) {
          state.chart.changeData(state.data);
        } else {
          nextTick(() => {
            initChart();
          });
        }
      }
    };
    onMounted(() => {
      registerTheme("chartTheme", common.chartTheme);
      getData();
    });

    onBeforeUnmount(() => {
      const chartBox = document.getElementById(state.chartId);
      if (chartBox) {
        chartBox.innerHTML = "";
      }
    });
    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
@import "../../styles/common.less";
</style>
